// 全局数据变量
let booksData = [];
let usersData = [];
let categoriesData = [];
let authorsData = [];
let currentDeleteItem = null;

// 格式化日期时间函数
function formatDateTime(dateObj) {
  if (!dateObj) return "未知时间";

  // 处理可能的日期格式差异
  const pad = (n) => n.toString().padStart(2, "0");

  // 兼容不同的日期对象结构
  const year = dateObj.year || dateObj.getFullYear();

  // 处理month的不同表示方式
  const month = dateObj.monthValue
    ? pad(dateObj.monthValue)
    : dateObj.month
    ? pad(dateObj.month + 1) // JavaScript月份是0-11
    : pad(dateObj.getMonth() + 1);

  const day = dateObj.dayOfMonth || dateObj.date || dateObj.getDate();
  const hours = dateObj.hour || dateObj.getHours() || 0;
  const minutes = dateObj.minute || dateObj.getMinutes() || 0;
  const seconds = dateObj.second || dateObj.getSeconds() || 0;

  return `${year}-${pad(month)}-${pad(day)} ${pad(hours)}:${pad(minutes)}:${pad(
    seconds
  )}`;
}

// 查询作者信息
function selectAuthor() {
  $.ajax({
    type: "GET",
    url: "selectAuthorAll.do",
    success: function (data) {
      authorsData = data.data;
      // console.log(authorsData);
      renderAuthorTable(authorsData);
    },
  });
}

// 获取书本详细信息
function getBookAll() {
  $.ajax({
    type: "GET",
    url: "selectBook.do",
    success: function (data) {
      booksData = data.data.data;
      // console.log(data.data);
      renderBookTable(booksData);
    },
  });
}

// 查询用户信息
function selectUser() {
  $.ajax({
    type: "GET",
    url: "selectUser.do",
    success: function (data) {
      usersData = data.data;
      renderUserTable(usersData);
    },
  });
}
// 查询分类信息
function selectCategory() {
  $.ajax({
    type: "GET",
    url: "selectCategory.do",
    success: function (data) {
      categoriesData = data.data;
      console.log(categoriesData);
      renderCategor(categoriesData);
    },
  });
}

// 渲染书籍表格
function renderBookTable(books) {
  const $tableBody = $(".book-list").empty();

  if (books != null && books.length > 0) {
    $.each(books, function (index, book) {
      // 创建列表项元素
      const $tr = $(`<tr data-id="${book.bookId}"></tr>`);
      // 设置列表项HTML内容
      $tr.html(`<td>${book.bookId}</td>
                        <td>${book.bookName}</td>
                        <td>${book.bookWriter}</td>
                        <td>${book.bookType}</td>
                        <td><span class="status ${
                          book.bookState === "1" ? "inactive" : "active"
                        }">${book.bookState === "1" ? "冻结" : "正常"}</span></td>
                        <td>
                            <div class="actions">
                                <button class="action-btn" data-action="view" data-id="${
                                  book.bookId
                                }"><i class="fa fa-eye"></i></button>
                                <button class="action-btn" data-action="edit" data-id="${
                                  book.bookId
                                }"><i class="fa fa-edit"></i></button>
                                <button class="action-btn" data-action="delete" data-id="${
                                  book.bookId
                                }" data-type="book"><i class="fa fa-trash"></i></button>
                            </div>
                        </td>`);
      // 添加到列表容器
      $tableBody.append($tr);
    });
  } else {
    $tableBody.html(
      '<tr><td colspan="7" class="text-center">暂无书籍数据</td></tr>'
    );
  }
}

// 渲染用户表格
function renderUserTable(users) {
  const $tableBody = $(".user-list").empty();

  if (users != null && users.length > 0) {
    $.each(users, function (index, user) {
      // 创建列表项元素
      const $tr = $(`<tr data-id="${user.userId}"></tr>`);
      console.log(user.status);
      // 设置列表项HTML内容
      $tr.html(`<td>${user.userId}</td>
                        
                        <td>${user.username}</td>
                        <td>${user.password}</td>
                        <td>${formatDateTime(user.registerTime)}</td>
                        <td><span class="status ${
                          user.status ? "active" : "inactive"
                        }">${user.status ? "正常" : "禁用"}</span></td>
                        <td>
                            <div class="actions">
                                <button class="action-btn" data-action="view" data-id="${
                                  user.userId
                                }"><i class="fa fa-eye"></i></button>
                                <button class="action-btn" data-action="edit" data-id="${
                                  user.userId
                                }"><i class="fa fa-edit"></i></button>
                                <button class="action-btn" data-action="delete" data-id="${
                                  user.userId
                                }" data-type="user"><i class="fa fa-trash"></i></button>
                            </div>
                        </td>`);
      // 添加到列表容器
      $tableBody.append($tr);
    });
  } else {
    $tableBody.html(
      '<tr><td colspan="6" class="text-center">暂无用户数据</td></tr>'
    );
  }
}

// 渲染分类表格
function renderCategoryTable(categories) {
  const $tableBody = $(".category-list").empty();

  if (categories != null && categories.length > 0) {
    $.each(categories, function (index, category) {
      // 创建列表项元素
      const $tr = $(`<tr data-id="${category.categoryId}"></tr>`);
      // 设置列表项HTML内容
      $tr.html(`<td>${category.categoryId}</td>
                  <td>${category.categoryName}</td>
                  <td>${category.parentId}</td>
                  <td>${formatDateTime(category.createTime)}</td>
                  <td>
                      <div class="actions">
                          <button class="action-btn" data-action="view" data-id="${
                            category.categoryId
                          }"><i class="fa fa-eye"></i></button>
                          <button class="action-btn" data-action="edit" data-id="${
                            category.categoryId
                          }"><i class="fa fa-edit"></i></button>
                          <button class="action-btn" data-action="delete" data-id="${
                            category.categoryId
                          }" data-type="category"><i class="fa fa-trash"></i></button>
                      </div>
                  </td>`);
      // 添加到列表容器
      $tableBody.append($tr);
    });
  } else {
    $tableBody.html(
      '<tr><td colspan="5" class="text-center">暂无分类数据</td></tr>'
    );
  }
}

// 渲染作者表格
function renderAuthorTable(authors) {
  const $tableBody = $(".author-list").empty();

  if (authors != null && authors.length > 0) {
    $.each(authors, function (index, author) {
      // 创建列表项元素
      const $tr = $(`<tr data-id="${author.authorId}"></tr>`);
      // 设置列表项HTML内容
      $tr.html(`<td>${author.authorId}</td>
                  <td>${author.penName}</td>
                  <td>${author.birthPlace}</td>
                  <td>${author.worksCount}</td>
                  <td>
                      <div class="actions">
                          <button class="action-btn" data-action="view" data-id="${author.authorId}"><i class="fa fa-eye"></i></button>
                          <button class="action-btn" data-action="edit" data-id="${author.authorId}"><i class="fa fa-edit"></i></button>
                          <button class="action-btn" data-action="delete" data-id="${author.authorId}" data-type="author"><i class="fa fa-trash"></i></button>
                      </div>
                  </td>`);
      // 添加到列表容器
      $tableBody.append($tr);
    });
  } else {
    $tableBody.html(
      '<tr><td colspan="5" class="text-center">暂无作者数据</td></tr>'
    );
  }
}

function renderCategor(categories) {
  const $select = $("#editBookCategory").empty();
  $select.append('<option value="">请选择分类</option>');

  if (categories && categories.length > 0) {
    categories.forEach((category) => {
      const $option = $("<option>")
        .val(category.minorName) // 使用分类名称作为值
        .text(category.minorName); // 使用分类名称作为显示文本

      $select.append($option);
    });
  }
}

$(document).ready(function () {
  // 初始化图表
  function initCharts() {
    var categoryCtx = document.getElementById("categoryChart").getContext("2d");
    new Chart(categoryCtx, {
      type: "doughnut",
      data: {
        labels: ["计算机", "文学", "历史", "科幻", "心理学", "其他"],
        datasets: [
          {
            data: [20, 18, 15, 12, 10, 25],
            backgroundColor: [
              "#165DFF",
              "#409EFF",
              "#67C23A",
              "#E6A23C",
              "#F56C6C",
              "#909399",
            ],
            borderWidth: 0,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: "right",
            labels: {
              padding: 20,
              usePointStyle: true,
              pointStyle: "circle",
            },
          },
          title: {
            display: true,
            text: "书籍分类分布",
            font: {
              size: 16,
            },
          },
        },
        cutout: "70%",
      },
    });
  }

  // 设置侧边栏菜单
  function setupSidebarMenu() {
    // 主菜单项点击事件
    $(".sidebar > ul > li > span").click(function () {
      $(this).parent().toggleClass("active");
    });

    // 菜单链接点击事件
    $(".sidebar a[data-target]").click(function (e) {
      e.preventDefault();
      e.stopPropagation();

      // 更新活动菜单项
      $(".sidebar a.active").removeClass("active");
      $(this).addClass("active");

      // 显示目标内容页
      var target = $(this).data("target");
      $(".content-page").removeClass("active");
      $("#" + target).addClass("active");
    });
  }

  // 设置编辑按钮事件
  function setupEditButtons() {
    // 书籍编辑按钮
    $(document).on(
      "click",
      '.book-list .action-btn[data-action="edit"]',
      function () {
        const row = $(this).closest("tr");
        const bookId = row.data("id");

        // 从行中获取数据
        const bookData = {
          id: bookId,
          name: row.find("td:eq(1)").text(),
          author: row.find("td:eq(2)").text(),
          category: row.find("td:eq(3)").text(),
          status: row.find(".status").hasClass("active")
            ? "active"
            : "inactive",
          cover: row.find(".book-cover").attr("src"),
        };

        // 填充模态框
        $("#editBookId").val(bookData.id);
        $("#editBookName").val(bookData.name);
        $("#editBookAuthor").val(bookData.author);
        $("#editBookCategory").val(bookData.category);
        $("#editBookStatus").val(bookData.status);
        $("#editBookCoverPreview").attr("src", bookData.cover);

        // 处理分类默认选中
        if (bookData.category) {
          $("#editBookCategory option[value='" + bookData.category + "']").prop(
            "selected",
            true
          );
        } else {
          // 没有分类时选择默认选项
          $("#editBookCategory option:first").prop("selected", true);
        }

        // 显示模态框
        $("#editBookModal").css("display", "flex");
      }
    );

    // 用户编辑按钮
    $(document).on(
      "click",
      '.user-list .action-btn[data-action="edit"]',
      function () {
        const row = $(this).closest("tr");
        const userId = row.data("id");

        // 从行中获取数据
        const userData = {
          id: userId,
          name: row.find("td:eq(1)").text(),
          password: row.find("td:eq(2)").text(),
          status: row.find(".status").hasClass("active")
            ? "active"
            : "inactive",
          avatar: row.find(".user-avatar").attr("src"),
        };
        console.log(userData.password);
        // 填充模态框
        $("#editUserId").val(userData.id);
        $("#editUserName").val(userData.name);
        $("#editUserPassword").val(userData.password);
        $("#editUserStatus").val(userData.status);
        $("#editUserAvatarPreview").attr("src", userData.avatar);
        // 显示模态框
        $("#editUserModal").css("display", "flex");
      }
    );

    // 作者编辑按钮
    $(document).on(
      "click",
      '.author-list .action-btn[data-action="edit"]',
      function () {
        const row = $(this).closest("tr");
        const authorId = row.data("id");

        // 从行中获取数据
        const authorData = {
          id: authorId,
          name: row.find("td:eq(1)").text(),
          nationality: row.find("td:eq(2)").text(),
          worksCount: row.find("td:eq(3)").text(),
        };

        // 填充模态框
        $("#editAuthorId").val(authorData.id);
        $("#editAuthorName").val(authorData.name);
        $("#editAuthorNationality").val(authorData.nationality);
        $("#editAuthorWorksCount").val(authorData.worksCount);

        // 显示模态框
        $("#editAuthorModal").css("display", "flex");
      }
    );
  }

  // 设置保存按钮事件
  function setupSaveButtons() {
    // 保存书籍编辑
    $("#saveEditBook").click(function () {
      const bookId = $("#editBookId").val();
      const bookName = $("#editBookName").val();
      const bookAuthor = $("#editBookAuthor").val();
      const bookCategory = $("#editBookCategory").val(); // 直接获取分类名称
      const bookStatus = $("#editBookStatus").val();

      // 更新表格中的行
      const row = $(`.book-list tr[data-id="${bookId}"]`);
      row.find("td:eq(1)").text(bookName);
      row.find("td:eq(2)").text(bookAuthor);
      row.find("td:eq(3)").text(bookCategory); // 保存分类名称

      const statusSpan = row.find(".status");
      statusSpan.text(bookStatus === "active" ? "正常" : "下架");
      statusSpan.removeClass("active inactive").addClass(bookStatus);

      // 更新全局数据
      const bookIndex = booksData.findIndex((b) => b.bookId == bookId);
      if (bookIndex !== -1) {
        booksData[bookIndex].bookName = bookName;
        booksData[bookIndex].bookWriter = bookAuthor;
        booksData[bookIndex].bookType = bookCategory; // 存储分类名称
        booksData[bookIndex].bookState = bookStatus === "active" ? "1" : "0";
      }

      // 关闭模态框
      $("#editBookModal").hide();
      showToast("书籍信息更新成功", "success");
    });

    // 保存用户编辑
    $("#saveEditUser").click(function () {
      const userId = $("#editUserId").val();
      const userName = $("#editUserName").val();
      const userPhone = $("#editUserPassword").val();
      const userStatus = $("#editUserStatus").val();

      // 更新表格中的行
      const row = $(`.user-list tr[data-id="${userId}"]`);
      row.find("td:eq(1)").text(userName);
      row.find("td:eq(2)").text(userPhone);

      const statusSpan = row.find(".status");
      statusSpan.text(userStatus === "active" ? "正常" : "禁用");
      statusSpan.removeClass("active inactive").addClass(userStatus);

      // 更新全局数据
      const userIndex = usersData.findIndex((u) => u.userId == userId);
      if (userIndex !== -1) {
        usersData[userIndex].username = userName;
        usersData[userIndex].password = userPhone;
        usersData[userIndex].userState = userStatus === "active" ? 0 : 1;
      }

      $.ajax({
        type: "POST",
        url: "updateUser.do",
        data: {
          userId: userId,
          username: userName,
          password: userPhone,
          state: userStatus,
        },
      });
      // 关闭模态框
      $("#editUserModal").hide();
      showToast("用户信息更新成功", "success");
    });

    // 保存作者编辑
    $("#saveEditAuthor").click(function () {
      const authorId = $("#editAuthorId").val();
      const authorName = $("#editAuthorName").val();
      const authorNationality = $("#editAuthorNationality").val();
      const authorWorksCount = $("#editAuthorWorksCount").val();

      // 更新表格中的行
      const row = $(`.author-list tr[data-id="${authorId}"]`);
      row.find("td:eq(1)").text(authorName);
      row.find("td:eq(2)").text(authorNationality);
      row.find("td:eq(3)").text(authorWorksCount);

      // 更新全局数据
      const authorIndex = authorsData.findIndex((a) => a.authorId == authorId);
      if (authorIndex !== -1) {
        authorsData[authorIndex].penName = authorName;
        authorsData[authorIndex].birthPlace = authorNationality;
        authorsData[authorIndex].worksCount = authorWorksCount;
      }

      $.ajax({
        type: "POST",
        url: "updateAuthor.do",
        data: {
          authorId: authorId,
          authorName: authorName,
          authorNationality: authorNationality,
          authorWorksCount: authorWorksCount,
        },
      });

      // 关闭模态框
      $("#editAuthorModal").hide();
      showToast("作者信息更新成功", "success");
    });
  }

  // 设置关闭按钮事件
  function setupCloseButtons() {
    // 书籍模态框关闭
    $("#closeEditModal, #cancelEditBook").click(function () {
      $("#editBookModal").hide();
    });

    // 用户模态框关闭
    $("#closeEditUserModal, #cancelEditUser").click(function () {
      $("#editUserModal").hide();
    });

    // 作者模态框关闭
    $("#closeEditAuthorModal, #cancelEditAuthor").click(function () {
      $("#editAuthorModal").hide();
    });

    // 删除模态框关闭
    $("#closeDeleteModal, #cancelDelete").click(function () {
      $("#deleteConfirmModal").hide();
    });
  }

  // 设置图片预览功能
  function setupImagePreviews() {
    // 书籍封面预览
    $("#editBookCover").change(function (e) {
      if (this.files && this.files[0]) {
        const reader = new FileReader();
        reader.onload = function (e) {
          $("#editBookCoverPreview").attr("src", e.target.result);
        };
        reader.readAsDataURL(this.files[0]);
      }
    });

    // 用户头像预览
    $("#editUserAvatar").change(function (e) {
      if (this.files && this.files[0]) {
        const reader = new FileReader();
        reader.onload = function (e) {
          $("#editUserAvatarPreview").attr("src", e.target.result);
        };
        reader.readAsDataURL(this.files[0]);
      }
    });

    // 作者头像预览
    $("#editAuthorAvatar").change(function (e) {
      if (this.files && this.files[0]) {
        const reader = new FileReader();
        reader.onload = function (e) {
          $("#editAuthorAvatarPreview").attr("src", e.target.result);
        };
        reader.readAsDataURL(this.files[0]);
      }
    });
  }

  // 设置删除功能
  function setupDeleteFunctionality() {
    // 删除按钮点击事件
    $(document).on("click", '.action-btn[data-action="delete"]', function () {
      const itemId = $(this).data("id");
      const itemType = $(this).data("type");
      const row = $(this).closest("tr");

      // 根据类型获取正确的名称列
      let $nameCell;
      if (itemType === "author") {
        $nameCell = row.find("td:nth-child(2)");
      } else if (itemType === "category") {
        $nameCell = row.find("td:nth-child(2)");
      } else {
        $nameCell = row.find("td:nth-child(2)");
      }

      const itemName = $nameCell ? $nameCell.text() : "项目";

      // 设置当前删除项
      currentDeleteItem = {
        id: itemId,
        type: itemType,
        name: itemName,
      };

      // 更新删除确认框内容
      $("#deleteItemName").text(itemName);
      $("#deleteConfirmModal").css("display", "flex");
    });

    // 确认删除按钮
    $("#confirmDelete").click(function () {
      if (currentDeleteItem && currentDeleteItem.id && currentDeleteItem.type) {
        // 显示加载状态，防止重复点击
        $(this).prop("disabled", true);
        $(this).text("处理中...");

        deleteItem(currentDeleteItem.type, currentDeleteItem.id).always(
          function () {
            // 无论成功失败，重置按钮状态并关闭模态框
            $("#confirmDelete").prop("disabled", false);
            $("#confirmDelete").text("确认删除");
            $("#deleteConfirmModal").css("display", "none");
          }
        );
      }
    });
  }

  // 删除项目
  function deleteItem(type, id) {
    var deleteUrl = "";
    var itemName = "";

    // 根据删除类型确定API接口和提示信息
    switch (type) {
      case "book":
        deleteUrl = "deleteBook.do";
        itemName = "书籍";
        break;
      case "user":
        deleteUrl = "deleteUser.do";
        itemName = "用户";
        break;
      case "category":
        deleteUrl = "deleteCategory.do";
        itemName = "分类";
        break;
      case "author":
        deleteUrl = "deleteAuthor.do";
        itemName = "作家";
        break;
      default:
        showToast("未知删除类型", "error");
        return;
    }

    // 发送AJAX请求到后端
    return $.ajax({
      type: "POST",
      url: deleteUrl,
      data: { id: id },
      dataType: "json",
      beforeSend: function () {
        // 显示加载状态
        showToast("正在删除...", "info");
      },
      success: function (response) {
        // 后端返回成功
        if (response.success) {
          // 根据类型更新前端UI和全局数据
          const rowSelector = 'tr[data-id="' + id + '"]';

          switch (type) {
            case "book":
              booksData = booksData.filter((book) => book.bookId != id);
              break;
            case "user":
              usersData = usersData.filter((user) => user.userId != id);
              break;
            case "category":
              categoriesData = categoriesData.filter(
                (category) => category.categoryId != id
              );
              renderCategor(categoriesData);
              break;
            case "author":
              authorsData = authorsData.filter(
                (author) => author.authorId != id
              );
              break;
          }

          // 移除DOM元素
          const itemRow = document.querySelector(
            "." + type + "-list " + rowSelector
          );
          if (itemRow) {
            itemRow.remove();
          }

          showToast(itemName + "删除成功", "success");
        } else {
          // 后端返回失败
          showToast(response.message || itemName + "删除失败", "error");
        }
      },
      error: function (xhr, status, error) {
        // AJAX请求错误处理
        showToast("删除请求失败: " + error, "error");
        console.error("删除请求错误:", error);
      },
    });
  }

  // 点击模态框外部关闭模态框
  window.addEventListener("click", function (event) {
    if (event.target.classList.contains("modal")) {
      event.target.style.display = "none";
    }
  });

  // 显示操作提示
  function showToast(message, type) {
    const toast = $("#toast");
    toast.text(message);
    toast.removeClass("show success error warning info");
    toast.addClass("show " + type);

    setTimeout(function () {
      toast.removeClass("show success error warning info");
    }, 3000);
  }

  // 初始化所有功能
  function init() {
    initCharts();
    setupSidebarMenu();
    setupEditButtons();
    setupSaveButtons();
    setupCloseButtons();
    setupImagePreviews();
    setupDeleteFunctionality();

    // 加载数据
    selectAuthor();
    getBookAll();
    selectUser();
    selectCategory();
  }

  // 启动初始化
  init();
});
